from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import View
from apps.home_page.models import UdwGuide, UdwCategoryOne, UdwCategoryTwo, UdwCategoryThree,\
                                   UdwKeyword, UdwNodice, UdwGoods, UdwSlideshow, UdwGoodsInfo,\
                                   UdwGoodsComment, UdwOrder, UdwUser, UdwUserSite, UdwCoupon,\
                                   UdwMyCoupon, UdwUserMoney, UdwShoppingCart

from django.db.models import F, Q, Sum
from django.core.paginator import Paginator

#首页

import datetime



#首页
class Index(View):
    def get(self, request):
        #首页导航栏
        guide = UdwGuide.objects.filter(guide_status=1).order_by('guide_order')
        #一级分类
        info_one = []
        one = UdwCategoryOne.objects.filter(category_one_status=1)
        for i in one:
            print(i.category_one_name)
            a = {}
            a[i.category_one_id] = i.category_one_name
            info_one.append(a)
        #二级分类
        info_two = []
        for i in info_one:
            for ii in i.keys():
                twos = UdwCategoryTwo.objects.filter(Q(one_id=int(ii))&Q(category_two_status=1)).order_by('category_two_order')
                for two in twos:
                    b = {}
                    b[two.one_id] = {two.category_two_id:two.category_two_name}
                    info_two.append(b)
        #三级分类
        info_three = []
        threes = UdwCategoryThree.objects.filter(category_three_status=1).order_by('category_three_order')
        for three in threes:
            t = {}
            t[three.two_id] = three.category_three_name
            info_three.append(t)


        #搜索关键字,默认显示前7条
        keword = UdwKeyword.objects.filter(hot=1).order_by('order')
        if len(keword) > 7:
            keword = keword[0:7]
        # 平台公告，默认显示前15条
        nodice = UdwNodice.objects.filter(nodice_status=1).order_by('-nodice_time')
        if len(nodice) > 15:
            nodice = nodice[0:15]

        #轮播图
        show = UdwSlideshow.objects.filter(slideshow_status=1)

        grils = check_clothing('女装')
        boys = check_clothing('男装')

        user_id = request.session.get('id')

        if user_id:
            s_cart = UdwShoppingCart.objects.filter(user_id=user_id)
            cart_num = len(s_cart)
            user = UdwUser.objects.get(user_id=user_id)
            return render(request, 'index.html', {'info_one': info_one, 'info_two': info_two,
                                              'info_three': info_three, 'keword': keword,
                                              'nodice': nodice, 'grils': grils, 'boys': boys,
                                              'show': show, 'cart_num': cart_num, 'username': user.user_phone})
        else:
            return render(request, 'index.html', {'info_one': info_one, 'info_two': info_two,
                                                  'info_three': info_three, 'keword': keword,
                                                  'nodice': nodice, 'grils': grils, 'boys': boys,
                                                  'show': show})

    def post(self, request):
        pass


def check_clothing(name):
    one_id = UdwCategoryOne.objects.get(category_one_name=name).category_one_id
    two = UdwCategoryTwo.objects.filter(one_id=one_id)
    two_id = []
    for i in two:
        two_id.append(i.category_two_id)
    # print(two_id)
    threes_id = []
    for i in two_id:
        three = UdwCategoryThree.objects.filter(two_id=int(i))
        for ii in three:
            threes_id.append(ii.category_three_id)
    gs = []
    for i in threes_id:
        goods = UdwGoods.objects.filter(three_id=int(i))
        if len(goods) > 8:
            goods = goods[0:8]
        for good in goods:
            gs.append(good)
    return gs







#企业介绍
class Company_profile(View):
    def get(self, request):
        return render(request, 'temp_article/udai_article10.html')

    def post(self, request):
        pass


#新手上路
class Green_hand(View):
    def get(self, request):
        return render(request, 'temp_article/udai_article5.html')
    def post(self, request):
        pass

#X袋学堂
class Class_room(View):
    def get(self, request):
        return render(request, 'class_room.html')

    def post(self, request):
        pass

#企业账号
class Enterprise_id(View):
    def get(self, request):
        return render(request, 'enterprise_id.html')

    def post(self, request):
        pass


#诚信合约
class Udai_contract(View):
    def get(self, request):
        return render(request, 'udai_contract.html')

    def post(self, request):
        pass


#下架通知
class Item_remove(View):
    def get(self, request):
        return render(request, 'item_remove.html')

    def post(self, request):
        pass


#平台公告
# class Udai_notice(View, id=1):
#     def get(self, request):
#         notice = UdwNodice.objects.filter(nodice_status=1).order_by('nodice_time')
#         return render(request, 'udai_notice.html', {'nodice': notice})
#
#     def post(self, request):
#
#         pass

# #点击公告显示内容
# def notice(request, id):
#     one_notice = UdwNodice.objects.get(nodice_id=int(id))  # 查找用户进入的是哪个公告
#     return render(request, 'udai_notice.html', {'one_notice': one_notice,})


#平台公告分页
def page(request, pindex, id):
    notice = UdwNodice.objects.filter(nodice_status=1).order_by('-nodice_time')   #所有公告，按时间进行排序
    one_notice = UdwNodice.objects.get(nodice_id=int(id))  # 查找用户进入的是哪个公告
    paginator = Paginator(notice, 5)    #实例化paginator
    if pindex == "": # django中默认返回空值，所以加以判断，并设置默认值为1
        pindex = 1
    else:
        int(pindex)
    page = paginator.page(pindex)
    return render(request, 'udai_notice.html', {'page': page, 'one_notice': one_notice})







#热卖专区
class Item_sale_page(View):
    def get(self, request):
        return render(request, 'item_sale_page.html')

    def post(self, request):
        return render(request, 'udai_shopcart_pay.html')



#商品详情
class  Item_show(View):
    def get(self, request, id):
        user_id = request.session.get('id')    #获取session
        gd = UdwGoods.objects.get(goods_id=id)
        goods_info = UdwGoodsInfo.objects.filter(Q(goods_id=id) & Q(goods_audit_status=1) & Q(goods_publish_status=1))
        color = []
        size = []
        num = 0  # 库存数量
        sales = 0  # 销量
        comment_int = 0  # 评论数
        integral = None
        data_time = None
        for good in goods_info:
            sales += good.goods_info_sales
            num += good.goods_info_num
            color.append(good.goods_info_color)
            size.append(good.goods_info_size)
            comment = len(UdwGoodsComment.objects.filter(goods_info_id=good.goods_info_id))
            comment_int += comment
            integral = good.goods_info_intergral
            data_time = good.goods_modified_time
            #     print("评论数:{}".format(comment))
            # print("销量:{}".format(sales), "数量:{}".format(num), "价格:{}".format(gd.goods_price),
            #       "评论数:{}".format(comment_int), "可返积分:{}".format(integral),
            #       "上架时间:{}".format(data_time), set(color), set(size))
        keword = UdwKeyword.objects.filter(hot=1).order_by('order')
        if len(keword) > 7:
            keword = keword[0:7]
        if not user_id:
            return render(request, 'item_show.html', {'good_name': gd.goods_name,
                                                      'color': set(color),
                                                      'size': set(size),
                                                      'sales': sales, 'num': num,
                                                      'comment_int': comment_int,
                                                      'price': gd.goods_price,
                                                      'integral': integral,
                                                      'data_time': str(data_time)[0:10],
                                                      'keword': keword,
                                                      'g_id': gd.goods_id})
        else:
            s_cart = UdwShoppingCart.objects.filter(user_id=user_id)
            cart_num = len(s_cart)
            user = UdwUser.objects.get(user_id=user_id)
            return render(request, 'item_show.html', {'good_name': gd.goods_name,
                                                          'color': set(color),
                                                          'size': set(size),
                                                          'sales': sales, 'num': num,
                                                          'comment_int': comment_int,
                                                          'price': gd.goods_price,
                                                          'integral': integral,
                                                          'data_time': str(data_time)[0:10],
                                                          'keword': keword,
                                                          'g_id': gd.goods_id,
                                                          'username': user.user_phone,
                                                          'cart_num': cart_num})

    def post(self,request,id):
        color = request.POST.get('color')
        size = request.POST.get('size')
        number = request.POST.get('number')
        print(id, color, size, number)
        if not all([color, size, number]):
            return HttpResponse('信息不完整')
        goods_info = UdwGoodsInfo.objects.get(Q(goods_id=int(id))&Q(goods_info_color=color)&Q(goods_info_size=size))
        num = goods_info.goods_info_num       #商品库存数量
        if int(number) > num:
            return HttpResponse('数量不足')
        #判断是否登录
        user_id = request.session.get('id')
        if not user_id:
            return redirect('login_register:login')
        one_money = round(goods_info.goods_info_price * 0.8, 2)   #每一件的价格
        payable_amount = int(number) * one_money         #总价格
        create_time = datetime.datetime.now()
        point = goods_info.goods_info_intergral

        user = UdwUser.objects.get(user_id=user_id)
        #生成订单，staus为1，pay_status=0 待付款，
        UdwOrder.objects.create(user_id=user_id, goods_info_id=goods_info.goods_info_id, goods_number=number,
                                status=1, pay_status=0, telphone=user.user_phone, payable_amount=payable_amount,
                                create_time=create_time, point=point
                                )
        # #用户增加积分,需要用户完成订单在增加积分
        # user.user_integral += point
        # user.save()
        #商品数量减去
        goods_info.goods_info_num -= int(number)
        goods_info.save()
        return redirect('home_page:pay')






class Pay(View):
    def get(self, request):
        #获取当前用户id
        user_id = request.session.get('id')
        user = UdwUser.objects.get(user_id=user_id)
        #找用户所有的地址
        sites = UdwUserSite.objects.filter(Q(user_id=user_id)&Q(status=1))
        de_site = None
        ss = []
        if len(sites)==1:
            for site in sites:
                site.default = '1'
                site.save()
                de_site = site
        else:
            for i in sites:
                if i.default == '1':
                    de_site = i
                else:
                    ss.append(i)
        #显示确认订单信息
        order = UdwOrder.objects.filter(user_id=user_id).order_by('-create_time')[0]
        order_time = order.create_time.strftime('%Y-%m-%d %T')
        #获取用户购买商品的信息
        good_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id)
        #获取商品名字
        good = UdwGoods.objects.get(goods_id=good_info.goods_id)

        # #查看当前用户能使用的优惠券
        user_coupons = UdwMyCoupon.objects.filter(user_id=user_id)
        # 存储当前商品可用的优惠券
        coupon_list = []
        for user_coupon in user_coupons:
            try:
                coupon = UdwCoupon.objects.get(Q(coupon_id=user_coupon.coupon_id) & Q(goods_id=good.goods_id))
            except UdwCoupon.DoesNotExist:
                pass
            else:
                if coupon.meet_money <= order.payable_amount:    #判断订单金额是否满足优惠卷的最低使用规则
                    coupon_list.append(coupon)
        # 判断拿出的优惠券是否在时间期限内
        for cou in coupon_list:
            #datetime.datetime.now()得到的当前时间是offset-naive的，
            # 而另外一个却是offset-aware的，
            # 因此我们需要将这里的start转成与now一样的形式，可以这么做： .replace(tzinfo=None)
            start = cou.start_time.replace(tzinfo=None)
            now = datetime.datetime.now()
            end = cou.end_time.replace(tzinfo=None)
            if start < now < end:
                pass
            else:
                coupon_list.remove(cou)
        context = {
            'user': user,
            'username': user.user_phone,
            'de_site': de_site,
            'sites': ss,
            'good_info': good_info,
            'good': good,
            'order': order,
            'order_time': order_time,
            'coupon_list': coupon_list

        }
        return render(request, 'udai_shopcart_pay.html', context)

    def post(self, request):
        #获取前端提交的地址和支付方式和是否有优惠卷
        user_id = request.session.get('id')
        order = UdwOrder.objects.filter(user_id=user_id).order_by('-create_time')[0]
        site = request.POST.get('addr')
        pay_method = request.POST.get('pay-mode')
        coupon_id = request.POST.get('coupon')     #获取优惠卷id
        print(coupon_id)
        pay_amout = order.payable_amount   #应付商品金额
        if coupon_id != '-1':     #判断是否有可用优惠卷
            coupon = UdwCoupon.objects.get(coupon_id=coupon_id)
            pay_amout -= coupon.coupon_value    #实付金额等于应付金额减去优惠卷金额
        #找用户储存的余额
        user = UdwUser.objects.get(user_id=user_id)
        if pay_method == '1':
            #余额支付
            if user.user_integral >= pay_amout:
                user.user_integral -= pay_amout
                user.save()
                #订单表变更
                order.site_id = site
                order.pay_code = user.user_phone
                order.status = '2'
                order.pay_status = '1'
                order.distribution_status = '0'
                order.real_amount = pay_amout
                order.pay_time = datetime.datetime.now()
                order.save()
                #余额变动表
                UdwUserMoney.objects.create(user_id=user_id,
                                            money_source='1',
                                            money_amount=pay_amout,
                                            create_time=datetime.datetime.now())
                #我的优惠卷改为已用状态
                my_coupons = UdwMyCoupon.objects.filter(coupon_id=coupon_id)
                for mc in my_coupons:
                    mc.my_coupon_status = '1'
                    mc.save()
                return HttpResponse('订单支付成功')
            else:
                return HttpResponse('余额不足')

        elif pay_method == '2':
            return HttpResponse('此功能正在开发中')

        elif pay_method == '3':
            return HttpResponse('此功能正在开发中')

        else:
            return HttpResponse('请勾选付款方式')






